apiready = function() {
    var photoBrowser = api.require('photoBrowser');
    var iOSDialog = api.require('iOSDialog');
    var clipBoard = api.require('clipBoard');

    var app = new Vue({
        el:'#app',
        data:{
            iosTest:false,
            timer: 0,
            subTabIndex: 0,
            subTabs: [
                {text: '全部', status: 0},
                {text: '进行中', status: 1},
                {text: '待审核', status: 2},
                {text: '已完成', status: 3},
                {text: '仲裁中', status: 4},
                {text: '未通过', status: 5},
                {text: '已关闭', status: 6},
            ],
            
            taskId: 0,
            task: null,
            showTaskDetail: false,
            taskEndTimeStr: '',
            tabIndex: 0,
            commandsConfig: {},
            accepters: null,
            page: 1,
            hasMore: true,

            // 批量审核
            batchReviewIds: [],
        },
        computed: {
            limitOS: function(){
                var os = this.task.limited_os.systems;
                return os.join('、');
            },
            taskProgress: function(){
                var task = this.task;
                var progress = (task.total_accepts - task.total_surplus_accepts)/task.total_accepts * 100;
                return parseInt(progress)+'%';
            },
        },
        filters: {
            dateFormate: function(time){
                return utils.tsToDateFormat(time, 'yyyy-MM-dd hh:mm:ss');
            },
        },
        created: function(){
            this.taskId = api.pageParam.data.taskId;
        },
        methods:{
            getTaskDetail: function(){
                var _this = this;
                $.ajax({
                    url: '/task/detail?task_id='+this.taskId,
                    method: 'get',
                    success: function(res){
                        _this.task = res.data.task;
                        _this.taskEndCountDown();
                    },
                });
            },
            getCommands: function(){
                var _this = this;
                $.ajax({
                    url: '/task/step/all_opercommands',
                    method: 'get',
                    success: function(res){
                        _this.commandsConfig = _this.adapterOperCommands(res.data);

                    },
                });
            },
            getAccepters: function(){
                var _this = this;
                var status = this.subTabs[this.subTabIndex].status;
                var page = this.page;
                $.ajax({
                    url: '/task/accept/query_by_task?task_id='+this.taskId+'&status='+status+'&page='+page,
                    method: 'get',
                    success: function(res){
                        var accepters = res.data.records;
                        var hasMore = accepters.length >= res.data.limit;
                        if(page == 1){
                            _this.accepters = accepters;
                        }else{
                            _this.accepters = _this.accepters.concat(accepters);
                        }
                        _this.hasMore = hasMore;
                        _this.page += 1;
                    },
                    error: function(err){
                        if(page == 1 && err.code == 404){
                            _this.accepters = [];
                        }else{
                            $.toast(err.message);
                        }
                    }
                });
            },
            adapterOperCommands: function(data){
                var targets = data.targets;
                var commands = data.commands;
                var commandsConfig = {};
                var operations = [];
                for(var i=0; i<targets.length; i++){
                    commandsConfig[targets[i].name] = [];
                    operations = targets[i].operations;
                    for(var j = 0; j<operations.length; j++){
                        commandsConfig[targets[i].name].push(commands[operations[j]]);
                    }
                }
                return commandsConfig;
            },
            toggleShowTaskDetail: function(){
                this.showTaskDetail = !this.showTaskDetail;
            },
            taskEndCountDown: function(){
                this.timer = clearTimeout(this.timer);
                var _this = this;
                var taskOverTime = '任务已截止';
                var endTimeStamp = (parseInt(this.task.time_created) + this.task.deadline_time * 3600) * 1000;
                var diffTime = parseInt((endTimeStamp - Date.now()) / 1000);
                var day = Math.floor(diffTime / 3600 / 24);
                var hour = Math.floor(diffTime / 3600 % 24);
                var min = Math.floor(diffTime / 60 % 60);
                var sec = Math.floor(diffTime % 60);
            
                if(diffTime >= 3600*24){
                    taskOverTime = `${day}天${hour}小时${min}分${sec}秒`;
                }else if(diffTime >= 3600){
                    taskOverTime = `${hour}小时${min}分${sec}秒`;
                }else if(diffTime >= 60){
                    taskOverTime = `${min}分${sec}秒`;
                }else if(diffTime > 0){
                    taskOverTime = `${sec}秒`;
                }

                this.taskEndTimeStr = taskOverTime;

                if(diffTime <= 0){
                    this.timer = clearTimeout(this.timer);
                    return false;
                }
                this.timer = setTimeout(function(){
                    _this.taskEndCountDown()
                },1000);
            },
            changeTab: function(index){
                this.tabIndex = index;
            },
            changeSubTab: function(index){
                this.subTabIndex = index;
                this.page = 1;
                this.hasMore = true;
				this.accepters = null;
                this.getAccepters();
            },
            viewPicture: function(img){
                photoBrowser.open({
                    images: [img],
                    bgColor: '#000',
                    zoomEnabled: true,
                }, function(ret, err) {
                    if(ret.eventType == 'click'){
                        photoBrowser.close();
                    }else if(ret.eventType == 'longPress'){
                        var param = {title:"提示",items:["保存到系统相册"]};
                        iOSDialog.actionSheetDialog(param,function(ret, err){
                            if(ret.index == 1){
                                $.saveMediaToAlbum(img, function(){
                                    $.toast('图片已保存到系统相册');
                                });
                            }
                        });
                    }
                });
            },
            getStepsImgs: function(steps){
                if(!utils.isArray(steps)){
                    return false;
                }
                var imgs = [];
                var step = null;
                var item = null;
                for(var i=0; i<steps.length; i++){
                    step = steps[i];
                    for(var j=0; j<step.length; j++){
                        item = step[j];
                        if(utils.isArray(item)){
                            for(var k=0; k<item.length; k++){
                                if(item[k].type == 'CollectGallery'){
                                    imgs.push(item[k]);
                                }
                            }
                        }
                    }
                }
                return imgs;
            },
            getStepsCollectTxts: function(steps){
                if(!utils.isArray(steps)){
                    return false;
                }
                var collects = [];
                var step = null;
                for(var i=0; i<steps.length; i++){
                    step = steps[i];
                    for(var j=0; j<step.length; j++){
                        item = step[j];
                        if(item.type == 'CollectTextInfo'){
                            collects.push(item);
                        }
                        
                    }
                }
                return collects;
            },
            reviewCheck: function(id){
                var index = this.batchReviewIds.indexOf(id);
                if(index == -1){
                    this.batchReviewIds.push(id);
                }else{
                    this.batchReviewIds.splice(index, 1);
                }
            },
            approveAccept: function(ids){
                var _this = this;
                $.ajax({
                    url: '/task/accept/approve',
                    method: 'post',
                    data: {
                        ta_ids: ids,
                        approved: true
                    },
                    load: true,
                    success: function(res){
                        // _this.page = 1;
                        // _this.hasMore = true;
                        // _this.getAccepters();
                        // window.scrollTo(0,0);
                        var status = {
                            text: '已完成',
                            tag: 'Completed',
                            value: 3,
                        }
                        _this.batchReviewIds = [];
                        var list = _this.accepters;
                        var idList = ids.toString().split(',');
                        for(var i=0; i<list.length; i++){
                            if(idList.indexOf(list[i].id.toString()) >= 0){
                                _this.$set(_this.accepters[i], 'status', status);
                            }
                        }

                    },
                });
            },
            singleApprove: function(id, status){
                if(status){
                    this.approveAccept(id);
                }else{
                    $.openUrl('common/commonTitle','task/arbitration',{title:'提交仲裁', ids: id, status: false});
                }
            },
            batchApprove: function(){
				var that = this;
                var ids = this.batchReviewIds.join(',');
                var param = {title:"审核",items:["通过","不通过"]};
                iOSDialog.actionSheetDialog(param,function(ret, err){
                    if(ret.index == 1){
                        that.approveAccept(ids);
                    }else if(ret.index == 2){
                        $.openUrl('common/commonTitle','task/arbitration',{title:'提交仲裁', ids: ids, status: false});
                    }
                });
            },
            goArbitrationDetail: function(id){
                $.openUrl('my/newArbitrationDetail','my/newArbitrationDetail',{title:'仲裁详情', id: id, referer: 'publishDetail'});
            },
            onCommandAction: function(cmds, value){
                var command = cmds.command;
                var ext = cmds.ext;
                switch (command) {
                    case 'copy':
                        this.action_copy(value);
                        break;
                    case 'openWeb':
                        this.action_openWeb(value);
                        break;
                    case 'useWeb':
                        this.action_useWeb(value);
                        break;
                    case 'openApp':
                        this.action_openApp(ext, value);
                        break;
                }
            },
            action_copy: function(val){
                clipBoard.set({
                    value: val
                }, function(ret, err) {
                    if (ret && ret.status) {
                        $.toast('复制成功');
                    } else {
                        $.toast('复制失败');
                    }
                });
            },
            action_openWeb: function(val){
                var url = 'about:;';
                api.openApp({
                    uri: url,
                    iosUrl: url,
                }, function(ret, err) {
                    if (!ret) {
                        $.toast('打开浏览器失败');
                    }
                });
            },
            action_useWeb: function(val){
                val = val.trim();
                var httpStart = val.toLocaleLowerCase().indexOf('http');
                if(httpStart == -1){
                    $.toast('不是完整有效链接，打开失败');
                    return false;
                }
                var url = val.substr(httpStart);
                api.openApp({
                    uri: url,
                    iosUrl: url,
                }, function(ret, err) {
                    if (!ret || !ret.status) {
                        $.toast('打开浏览器失败');
                    }
                });
            },
            action_openApp: function(ext, val){
                let url = ext.replace(/(\{\$1\})/, val.trim());
                api.openApp({
                    uri: url,
                    iosUrl: url,
                }, function(ret, err) {
                    if (!ret || !ret.status) {
                        $.toast('APP打开失败');
                    }
                });
            },
        },
        mounted(){
            $.initJs(this);
            this.getTaskDetail();
            this.getAccepters();
            this.getCommands();

        }
    });

    //上拉加载
    api.addEventListener({
        name:'scrolltobottom',
        extra:{threshold:10}
    }, function(ret, err){
        if(app.tabIndex == 0 && app.hasMore){
            app.getAccepters();
        }
    });

    // 仲裁回调
    api.addEventListener({
        name: 'updateTaskPublishDetail'
    }, function(ret, err){
        if(!ret){
            return false;
        }
        var ids = ret.value.ids;
        var idList = ids.toString().split(',');
        var list = app.accepters;
        var status = {
            text: '仲裁中',
            tag: 'Arbitrating',
            value: 4,
        }
        app.batchReviewIds = [];
        for(var i=0; i<list.length; i++){
            if(idList.indexOf(list[i].id.toString()) >= 0){
                app.$set(app.accepters[i], 'status', status);
            }
        }
    });

    
}